import { menu } from '../../../app/decorator';
import BaseShap from './base/BaseShap';

const { ccclass, property } = cc._decorator;

function createEllipse(px: number, py: number, r: number, R: number, n: number): cc.Vec2[] {
    // const px = cenX; //椭圆中心点x坐标
    // const py = cenY; //椭圆中心点y坐标
    // const r = minR;   //椭圆短半径
    // const R = maxR; //椭圆长半径

    let result = [];

    const a = 360 / n;
    const scale = (R - r) / r;
    for (let i = 0; i < n; ++i) {
        const angle = (i * a) / 180 * Math.PI;
        const y = r * Math.sin(angle);
        const x = r * Math.cos(angle) * (1 + scale);
        const point = cc.v2(px + x, py + y);
        result.push(point);
    }

    return result;
}

@ccclass
@menu(__filename, '椭圆形')
export default class ShapEllipse extends BaseShap {
    @property
    _xRadius: number = 40;
    @property({
        tooltip: '半径'
    })
    get xRadius() { return this._xRadius; }
    set xRadius(value) {
        this._xRadius = value;
        this.node && this.node.emit('xRadius-change');
        this.node && this.node.emit('radius-change');
        this.refreshPoints();
    }

    @property
    _yRadius: number = 100;
    @property({
        tooltip: '半径'
    })
    get yRadius() { return this._yRadius; }
    set yRadius(value) {
        this._yRadius = value;
        this.node && this.node.emit('yRadius-change');
        this.node && this.node.emit('radius-change');
        this.refreshPoints();
    }

    @property
    _count: number = 20;
    @property({
        range: [4, 360, 1],
        step: 1,
        slide: true,
        tooltip: '点数量'
    })
    get count() { return this._count; }
    set count(value) {
        this._count = Math.round(value);
        this.node && this.node.emit('count-change');
        this.refreshPoints();
    }

    @property
    _points: cc.Vec2[] = [];
    @property({
        tooltip: '多边形顶点数组(至少四个)',
        type: [cc.Vec2]
    })
    get points() { return this._points; }

    onLoad() {
        if (this._points.length !== this.count) {
            this.refreshPoints();
        }
    }

    private refreshPoints() {
        this._points = createEllipse(this.offset.x, this.offset.y, this.xRadius, this.yRadius, this.count);
        this.node && this.node.emit('points-change');
    }

    contains(nodePoint: cc.Vec2): boolean {
        return cc.Intersection.pointInPolygon(nodePoint.sub(this.offset), this._points);
    }
}
